package com.eightbears.beboy.ui.user.activity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.eightbears.beboy.R;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.FriendsCache;
import com.eightbears.beboy.base.cache.GroupCache;
import com.eightbears.beboy.base.cache.GroupMemberCache;
import com.eightbears.beboy.base.cache.MessageStatusCache;
import com.eightbears.beboy.base.cache.TopUserCache;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.CommonUtils;
import com.eightbears.beboy.base.util.ErrorUtils;
import com.eightbears.beboy.base.util.GsonUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.util.okhttp.OkHttpUtils;
import com.eightbears.beboy.base.util.okhttp.callback.StringCallback;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.entity.UserEntity;
import com.eightbears.beboy.entity.event.TopUserEvent;
import com.eightbears.beboy.entity.status.Status_Error;
import com.eightbears.beboy.ui.chat.ui.activity.ChatActivity;
import com.eightbears.beboy.ui.chat.ui.activity.ChatComplaintActivity;
import com.eightbears.beboy.ui.chat.ui.activity.GroupPickContactsActivity;
import com.eightbears.greendao.Friends;
import com.eightbears.greendao.GroupList;
import com.eightbears.greendao.GroupMember;
import com.eightbears.greendao.MessageStatus;
import com.eightbears.greendao.TopEaseUser;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMGroupManager;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.exceptions.HyphenateException;
import com.socks.library.KLog;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.eightbears.beboy.base.util.CommonAPI.CONNECTION_STATUS_SUCCESS;
import static com.eightbears.beboy.base.util.CommonAPI.KEY_HTTP_HEADER;
import static com.eightbears.beboy.base.util.CommonAPI.URL_UPDATE_GROUP_ICON;
import static com.eightbears.beboy.ui.chat.ui.fragment.ChatFragment.PARAMS_TO_CHAT_USERNAME;

public class ChatUserInfoActivity extends BaseActivity {

    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.iv_head)
    ImageView iv_head;
    @BindView(R.id.tv_nickname)
    TextView tv_nickname;
    @BindView(R.id.tb_top_message)
    ToggleButton tb_top_message;
    @BindView(R.id.tb_close_message)
    ToggleButton tb_close_message;
    @BindView(R.id.ll_clear_message)
    LinearLayout ll_clear_message;

    private String username;
    private int position;
    private Friends mFriends;
    private UserEntity mUserEntity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_user_info);

        initView();
        initData();
        initEvent();
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);

        username = getIntent().getStringExtra(PARAMS_TO_CHAT_USERNAME);
        position = getIntent().getIntExtra(EaseConstant.EXTAR_POSITION, -1);
        mFriends = FriendsCache.getInstance(this).getCacheById(username);
        mUserEntity = SPUtil.getUser();
        if (mFriends == null){
            ShowToast.showShortToast(getString(R.string.text_no_friend));
            finish();
        }
        tv_title.setText(R.string.text_chat_setting);
    }

    @Override
    protected void initData() {
        setUserInfo();
    }

    private void setUserInfo() {
        tv_nickname.setText(mFriends.getNickname());
        CommonUtils.loadImageView(this, mFriends.getCover(), R.mipmap.default_head, iv_head);
        TopEaseUser topEaseUser = TopUserCache.getInstance(getBaseContext()).getCacheById(username);
        MessageStatus messageStatus = MessageStatusCache.getInstance(getBaseContext()).getCacheById(username);

        if(null != messageStatus) {
            tb_close_message.setChecked(true);
        } else {
            tb_close_message.setChecked(false);
        }

        if (null != topEaseUser) {
            tb_top_message.setChecked(true);
        } else {
            tb_top_message.setChecked(false);
        }
    }

    @Override
    protected void initEvent() {
        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });

        tb_top_message.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    EventBus.getDefault().post(new TopUserEvent(position, username, true));
                } else {
                    EventBus.getDefault().post(new TopUserEvent(position, username, false));
                }
            }
        });

        tb_close_message.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked) {
                    MessageStatusCache.getInstance(getBaseContext()).saveData(new MessageStatus(username));
                } else {
                    MessageStatusCache.getInstance(getBaseContext()).removeDataById(username);
                }
            }
        });
    }

    @OnClick(R.id.ll_clear_message)
    void clearMessage() {
        EventBus.getDefault().post(new TopUserEvent(-1, username, false));
    }

    @OnClick(R.id.ll_complaint)
    void complaint() {
        startLocalActivity(this, ChatComplaintActivity.class, PARAMS_TO_CHAT_USERNAME, username);
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.iv_create_room)
    void createRoom() {
        List<String> members = new ArrayList<>();
        members.add(username);
        startActivityForResult(
                new Intent(this, GroupPickContactsActivity.class)
                        .putExtra("groupName", mUserEntity.getData().getNickname() + "的群")
                        .putExtra("members", (Serializable) members)
                , 0);
    }

    EMGroup emGroup;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String st1 = getResources().getString(R.string.Is_to_create_a_group_chat);
        final String st2 = getResources().getString(R.string.Failed_to_create_groups);
        if (resultCode == RESULT_OK) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    final String groupName = mUserEntity.getData().getNickname() + "的群";
                    String[] members = data.getStringArrayExtra("newmembers");
                    try {
                        EMGroupManager.EMGroupOptions option = new EMGroupManager.EMGroupOptions();
                        option.maxUsers = 200;
                        String reason = getString(R.string.invite_join_group);
                        reason = EMClient.getInstance().getCurrentUser() + reason + groupName;
                        option.style = EMGroupManager.EMGroupStyle.EMGroupStylePublicOpenJoin;
                        emGroup = EMClient.getInstance().groupManager().createGroup(groupName, " ", members, reason, option);
                        addGroup();

                    } catch (final HyphenateException e) {
                        runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(ChatUserInfoActivity.this, st2 + e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                }
            }).start();
        }
    }

    public void addGroup() {
        OkHttpUtils.post().url(URL_UPDATE_GROUP_ICON)
                .addHeader(KEY_HTTP_HEADER, "Bearer "+ SPUtil.getAccessToken())
                .addParams("group_id", emGroup.getGroupId())
                .build().execute(new StringCallback() {
            @Override
            public void onResponse(String response) {
                if(response.contains(CONNECTION_STATUS_SUCCESS)){
                    runOnUiThread(new Runnable() {
                        public void run() {
                            GroupCache.getInstance(getApplication()).saveData(new GroupList(emGroup.getGroupId(), "", emGroup.getGroupName()));
                            GroupMemberCache.getInstance(getApplication()).saveData(new GroupMember(emGroup.getGroupId(), mUserEntity.getData().getUser_id()+""));
                            Intent intent = new Intent(ChatUserInfoActivity.this, ChatActivity.class);
                            intent.putExtra(CommonAPI.EXTRA_CHAT_TYPE, CommonAPI.CHATTYPE_GROUP);
                            intent.putExtra("userId",emGroup.getGroupId());
                            startActivity(intent);
                        }
                    });
                }
            }

            @Override
            public void onError(Call call, Exception e) {
                KLog.e(e.getMessage());
                Status_Error status_error = GsonUtil.fromJson(e.getMessage(), Status_Error.class);
                ErrorUtils.alertError(ChatUserInfoActivity.this, status_error);
            }

        });
    }
}
